package kyssion.leetcode.num1_50;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class code47_全排列2 {
    private List<List<Integer>> res = new ArrayList<>();
    private boolean[] used;

    /**
     * 类似46题没有什么好办法可以解决
     * @param nums
     * @return
     */
    public List<List<Integer>> permuteUnique(int[] nums) {
        if (nums == null || nums.length == 0) {
            return res;
        }
        List<Integer> p = new ArrayList<>();
        Arrays.sort(nums);
        used = new boolean[nums.length];
        generatePermuteUnique(nums, 0, p);
        return res;
    }

    private void generatePermuteUnique(int[] nums, int index, List<Integer> p) {
        if (index == nums.length) {
            res.add(new ArrayList<>(p));
        }
        for (int i = 0; i < nums.length; i++) {
            if (i > 0 && (nums[i] == nums[i - 1]) && !used[i - 1]) {//避免重复值
                continue;
            }
            if (used[i]) {//避免重复值
                continue;
            }
            p.add(nums[i]);
            used[i] = true;
            generatePermuteUnique(nums, index + 1, p);
            p.remove(p.size() - 1);
            used[i] = false;
        }
    }
}
